package socket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ChatClientGUI extends JFrame {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private String nickname;

    public ChatClientGUI() {
        setTitle("Chat Client");
        setSize(400, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 初始化组件
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);

        inputField = new JTextField(20); // 设置初始宽度为20个字符
        sendButton = new JButton("发送");

        // 添加按钮监听器
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage(inputField.getText());
                inputField.setText("");
            }
        });

        // 添加输入框的 Enter 键监听器
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage(inputField.getText());
                inputField.setText("");
            }
        });

        // 布局
        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(inputField);
        bottomPanel.add(sendButton);
        add(bottomPanel, BorderLayout.SOUTH);

        // 连接服务器
        connectToServer();

        // 显示窗口
        setVisible(true);
    }

    private void connectToServer() {
        try {
            System.out.println("正在连接服务端...");
            socket = new Socket("localhost", 8848);
            System.out.println("服务端连接成功");

            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));

            // 登录逻辑
            login();

            // 启动接收消息线程
            Thread receiveThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String message;
                        while ((message = in.readLine()) != null) {
                            chatArea.append(message + "\n");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            receiveThread.setDaemon(true);
            receiveThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void login() {
        boolean loggedIn = false;
        while (!loggedIn) {
            nickname = JOptionPane.showInputDialog(this, "请输入昵称:");
            if (nickname == null || nickname.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "用户名不能为空，请重新输入");
            } else {
                out.println(nickname);
                chatArea.append("欢迎你: " + nickname + ", 请开始聊天吧\n");
                loggedIn = true;
            }
        }
    }

    private void sendMessage(String message) {
        if (!message.isEmpty()) {
            out.println(message);
            chatArea.append(nickname + ": " + message + "\n");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new ChatClientGUI();
        });
    }
}

